import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Input, Button, Table, Modal, Pagination } from 'antd';
import { DEFAULT_PAGE_SIZE, DEFAULT_VALID_STATE } from '@/constants';
import styles from './index.less';

import Edit from './edit';

const { Content } = Layout;
const { confirm } = Modal;

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'title';
    this.state = {
      currentUnitName: '',
      constants: {
        titleTypes: []
      },
      query: {
        state: DEFAULT_VALID_STATE,
        unit_id: {
          id: -1
        }
      }
    }
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/queryTitleType',
      payload: {
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, titleTypes: data } });
        }
      }
    });
    this.queryData(1, DEFAULT_PAGE_SIZE);
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增头衔', editData: {} }
    })
  }

  editBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑头衔', editData: record }
    })
  }

  stopBtnClick = (record) => {
    confirm({
      title: '是否确认删除头衔?',
      content: Array.isArray(record) ? undefined : `头衔 [${record.title_name}]`,
      onOk: () => {
        const { query = {} } = this.state;
        const { dispatch, modular } = this.props;
        const { current, pageSize } = modular;

        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            data: Array.isArray(record) ? record.map(item => item.id) : record.id,
            ...query,
            current,
            pageSize
          }
        });
      },
      onCancel() { }
    });
  }

  searchBtnClick = () => {
    const { modular } = this.props;
    const { pageSize = DEFAULT_PAGE_SIZE } = modular;

    this.queryData(1, pageSize);
  }

  onChange = (current, pageSize) => {
    const { query = {} } = this.state;
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current,
        pageSize
      }
    });
  }

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize);
  }

  onOk = () => {
    const { query = {} } = this.state;
    const { dispatch, form, modular } = this.props;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields((err, values) => {
      if (!err) {
        const data = {
          ...editData,
          ...values
        };
        if (!editData.id) {
          data.state = DEFAULT_VALID_STATE;
        }
        dispatch({
          type: `${this.modularName}/saveOrUpdateData`,
          payload: {
            id: editData.id,
            data,
            ...query,
            current,
            pageSize
          }
        });
      }
    });
  }

  queryData = (current, pageSize) => {
    const { query = {} } = this.state;

    this.props.dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current,
        pageSize
      }
    });
  }

  render() {
    const { currentUnitName, constants = {}, query = {}, selectedRows = [] } = this.state;
    const { titleTypes = [] } = constants;
    const { dispatch, form, loading, modular } = this.props;
    const { data, current = 1, pageSize = DEFAULT_PAGE_SIZE, total = 0, rowKey, visible, editData = {} } = modular;

    const columns = [
      {
        title: '头衔类别',
        dataIndex: 'title_type',
        ellipsis: true,
        render: (text, record) => {
          if (record && record.title_type) {
            return record.title_type.type_name;
          }
          return '-'
        }
      },
      {
        title: '值班头衔',
        dataIndex: 'title_name',
        ellipsis: true
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
            </div>
          );
        }
      }
    ];

    return (
      <Layout className={styles.basic_layout_wrapper}>
        {/* <div className={styles.title}>
          当前单位: <span style={{ color: 'rgb(27, 139, 236)' }}>{currentUnitName}</span>
        </div> */}
        <div className={styles.conditions_wrapper}>
          <Input placeholder='值班头衔' style={{ width: 240, marginRight: 16 }} value={query.title_name} onChange={e => this.setState({ query: { ...query, title_name: e.target.value || undefined } })} />
          <Button icon='search' type='primary' onClick={this.searchBtnClick}>搜索</Button>
        </div>
        <Content className={styles.conditions_wrapper} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            <div style={{ marginBottom: 16 }}>
              <Button icon='plus' type='primary' style={{ marginRight: 16 }} onClick={this.appendBtnClick}>新增头衔</Button>
              <Button icon='delete' type='danger' onClick={selectedRows && selectedRows.length > 0 ? this.stopBtnClick.bind(this, selectedRows) : undefined}>批量删除{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
            </div>
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={columns}
                dataSource={data}
                loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                pagination={false}
                rowKey={rowKey}
                rowSelection={{
                  onChange: (selectedRowKeys, rows) => {
                    this.setState({ selectedRows: [...selectedRows.filter(item => selectedRowKeys.includes(item.id) && !rows.map(row => row.id).includes(item.id)), ...rows] })
                  }
                }}
              />
            </Content>
            <div style={{ marginTop: 16 }}>
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                showQuickJumper
                showSizeChanger
                showTotal={(total, range) => `共有 ${total} 条数据`}
                onChange={this.onChange}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          </Layout>
        </Content>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={480}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            })
          }}
        >
          <Edit form={form} data={editData} titleTypes={titleTypes} />
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, title }) => ({ loading, modular: title }))(Form.create()(Index));